import { Dir } from "../type/dir";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

	@property([cc.SpriteFrame])
	spriteFrame: cc.SpriteFrame[] = [];

	@property(cc.Prefab)
	bulletPrefab: cc.Prefab = null;

	@property
	speed: number = 300;

	dir: Dir = Dir.up;

	moveDir: cc.Vec2 = cc.v2();

	onLoad() {

		this.node.on('setDir', this.setDir, this);
	}

	start() {

	}

	update(dt) {
		this.node.x += this.speed * dt * this.moveDir.x;
		this.node.y += this.speed * dt * this.moveDir.y;
	}



	setDir(dir: Dir) {
		if (dir == Dir.idle) {
			this.moveDir = cc.v2();
			return
		}
		if (this.spriteFrame.length < 4) {
			return;
		}
		let sprite = this.node.getComponent(cc.Sprite);
		sprite.spriteFrame = this.spriteFrame[dir];
		this.dir = dir;
		switch (dir) {
			case Dir.up:
				this.moveDir = cc.v2(0, 1)
				break;
			case Dir.right:
				this.moveDir = cc.v2(1, 0)
				break;
			case Dir.down:
				this.moveDir = cc.v2(0, -1)
				break;
			case Dir.left:
				this.moveDir = cc.v2(-1, 0)
				break;
			default:
				this.moveDir = cc.v2();
		}
	}

	fire() {
		let bullet = cc.instantiate(this.bulletPrefab);
		bullet.position = this.node.position;
		this.node.parent.addChild(bullet);
		bullet.emit('setDir', this.dir);

	}
}
